const mongoose = require('mongoose')

// 地址模型
const addressSchema = new mongoose.Schema({
  // 地址ID
  id: {
    type: String,
    required: true,
    unique: true
  },

  // 联系人信息
  name: {
    type: String,
    required: true
  },
  phone: {
    type: String,
    required: true
  },

  // 地址信息
  fullAddress: {
    type: String,
    required: true
  },

  // 是否为默认地址
  isDefault: {
    type: Boolean,
    default: false
  },

  // 用户ID
  userId: {
    type: String,
    required: true
  },

  // 创建和更新时间
  createTime: {
    type: Date,
    default: Date.now
  },
  updateTime: {
    type: Date,
    default: Date.now
  }
})

// 更新时间中间件
addressSchema.pre('save', function(next) {
  this.updateTime = new Date()
  next()
})

// 生成地址ID
addressSchema.statics.generateId = function() {
  return 'addr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 设置默认地址时，将其他地址设为非默认
addressSchema.statics.setDefaultAddress = async function(userId, addressId) {
  // 先将该用户的所有地址设为非默认
  await this.updateMany(
    { userId: userId },
    { isDefault: false }
  )
  
  // 将指定地址设为默认
  return await this.updateOne(
    { id: addressId, userId: userId },
    { isDefault: true }
  )
}

module.exports = mongoose.model('Address', addressSchema)
